import OpenAI from "openai"
import dotenv from "dotenv"
import http from "http";

dotenv.config();  // 让node运行时去读取.env中的内容

const client = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
    baseURL: process.env.OPENAI_BASE_URL
})

// 连接大模型
const getCompletion = async (prompt) => {
    // 用户说的话
    const messages = [{
        role: 'user',
        content: prompt
    }]
    // chat
    const response = await client.chat.completions.create({
        model: 'gpt-4o',
        messages: messages,
        temperature: 0.1,
        max_tokens: 100
    })
    return response.choices[0].message.content
}



// 跟ai交互
const main = async (message) => {
    const user_message = message
    const prompt = `请帮我翻译一下的文字到${user_message[1]}，只需要给出${user_message[1]}单词，不需要多余的解释"${user_message[0]}"`
    const result = await getCompletion(prompt)
    // console.log(result);
    return result
}

const server = http.createServer(async (req, res) => {
    // 允许跨域
    res.writeHead(200, {
        "access-control-allow-origin": '*'
    });

    // 获取到前端给我的参数
    const query = new URL(req.url, `http://${req.headers.host}`).searchParams;
    // console.log(query.get('inputText'));
    const inputText = query.get('inputText')
    const to = query.get('to')
    console.log(to);

    const message = [
        inputText,
        to
    ]
    const result = await main(message)
    res.end(result)
    // res.end("Hello, World!");
})

server.listen(3000, () => {
    console.log("server listening on 3000");
})